<?php

namespace App\Kuafu\User\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\User\Service\AuthService;

class RolePermissionMappings extends BaseModel
{
    use KfSoftDeletes;


    /**
     * 获取角色的所有权限 ID
     *
     * @param int $roleId
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getAllByRoleId(int $roleId)
    {
        return self::query()->where('roleId', $roleId)->get();
    }

    /**
     * 获取角色列表的所有权限 ID
     *
     * @param int $roleId
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getAllByRoleList(array $roleList)
    {
        $result = self::query()->whereIn('roleId', $roleList)->get()->unique('permissionId');
        return $result;
    }


    /**
     * 批量添加权限
     *
     * @param int $roleId
     * @param array $permissionIds
     * @return bool
     * @throws \App\Kuafu\User\Exceptions\UserException
     */
    public static function batchCreateData(int $roleId, array $permissionIds = [])
    {
        $insert = [];

        foreach ($permissionIds as $v) {
            $insert[] = [
                'roleId'       => $roleId,
                'permissionId' => $v,
                'createdAt'    => time(),
                'updatedAt'    => time(),
                'createdByUid' => AuthService::getUserId(),
                'updatedByUid' => AuthService::getUserId(),
            ];
        }

        $result = self::query()->insert($insert);

        return $result;
    }

    public static function batchUpdateData(int $roleId, array $permissionIds = [])
    {
        self::query()->where('roleId', $roleId)->delete();

        return self::batchCreateData($roleId, $permissionIds);
    }
}
